<script setup>
import WelfareItem from '@/components/WelfareItem.vue'
import { onMounted, ref } from 'vue'
import { showToast } from 'vant'
import {
  reqChangePacketStatus,
  reqGetPacketList,
  reqGetPacketDrawList,
  reqAddPacket,
} from '@/api/packet/index.js'
import { watch } from 'vue'

const packetList = ref([])
const loading = ref(false)
const page = ref(1)
const total = ref(0)
const refreshing = ref(false)
const showControl = ref(false)
const drawId = ref("")
const drawList = ref([])
const drawLoading = ref(false)
const drawPage = ref(1)
const drawTotal = ref(0)
const searchValue = ref("")
const isShowAdd = ref(false)
const packetParams = ref({
  title: '',
  amount: "",
  num: "",
  dh_code: false
})

const onLoadMore = () => {
  getPacketList()
}

onMounted(() => {
  refreshing.value = true
  getPacketList()
})

const getPacketList = async () => {
  try {
    const result = await reqGetPacketList({
      page: page.value,
      user_id: searchValue.value
    })
    if (result.code === 200) {
      if (page.value === 1) {
        packetList.value = result.data.data
      } else {
        packetList.value = [...packetList.value, ...result.data.data]
      }
      total.value = result.data.total
      page.value++
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

const onRefresh = () => {
  page.value = 1
  total.value = 0
  refreshing.value = true
  getPacketList()
}

const changeStatus = async ({ id, status }) => {
  const welfare = packetList.value.find((item) => item.id === id)
  const result = await reqChangePacketStatus(id, { status: status ? 1 : 0 })
  if (result.code === 200) {
    welfare.status = status ? 1 : 0
    showToast({
      type: 'success',
      message: '操作成功'
    })
  } else {
    showToast({
      type: 'fail',
      message: '操作失败'
    })
  }
}

const onShowControl = (id) => {
  showControl.value = true
  drawList.value = []
  drawPage.value = 1
  drawTotal.value = 0
  drawId.value = id
  getPacketDrawList()
}

const getPacketDrawList = async () => {
  drawLoading.value = true
  try {
    const result = await reqGetPacketDrawList(drawId.value, { page: drawPage.value })
    if (result.code === 200) {
      if (drawPage.value === 1) {
        drawList.value = result.data.data
      } else {
        drawList.value.push(...result.data.data)
      }
      drawTotal.value = result.data.total
      drawPage.value++
    }
  } finally {
    drawLoading.value = false
  }
}

const onSearch = () => {
  onRefresh()
}

watch(searchValue, (newVal) => {
  if (!newVal.trim()) {
    onRefresh()
  }
})

const addOfficePacket = () => {
  isShowAdd.value = true
  packetParams.value.title = ""
  packetParams.value.num = ""
  packetParams.value.amount = ""
  packetParams.value.dh_code = false
}

const handleAddPacket = async () => {
  packetParams.value.dh_code = packetParams.value.dh_code ? 1 : 0
  const result = await reqAddPacket(packetParams.value)
  if (result.code === 200) {
    showToast({ type: 'success', message: '操作成功' })
    onRefresh()
  } else {
    showToast({type: 'fail', message: '操作失败'})
  }
}
</script>

<template>
  <div class="packet-container">
    <van-search
      v-model="searchValue"
      show-action
      clearable
      placeholder="请输入用户id"
      @search="onSearch"
      clear-trigger="always"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <van-button type="primary" @click="addOfficePacket">添加官方红包</van-button>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="page * 10 >= total"
        finished-text="没有更多了"
        @load="onLoadMore"
      >
        <WelfareItem
          @showControl="onShowControl(welfare.id)"
          @change-status="changeStatus"
          v-for="welfare in packetList"
          :key="welfare.id"
          :welfare="welfare"
        />
      </van-list>
      <van-back-top bottom="10vh" />
    </van-pull-refresh>
    <van-dialog title="领取记录" v-model:show="showControl">
      <van-list
        v-model:loading="drawLoading"
        @load="getPacketDrawList"
        style="max-height: 50vh; overflow-y: scroll"
        :finished="drawPage * 10 >= drawTotal"
        finished-text="没有更多了"
      >
        <div v-for="item in drawList" :key="item.id" class="draw-item">
          <UserInfo
            style="flex: 1"
            :nickname="item.nickname"
            :avatar="item.avatar"
            :id="item.receives_user_id"
          ></UserInfo>
          <div>
            <div>已领{{ item.amount }} 剩余{{ item.surplus_amount }}</div>
            <div>{{ item.created_at }}</div>
          </div>
        </div>
      </van-list>
    </van-dialog>
    <van-dialog title="添加官方红包" show-cancel-button v-model:show="isShowAdd" @confirm="handleAddPacket">
      <van-field
          v-model="packetParams.title"
          type="text"
          label="标题"
          placeholder="请输入红包标题"
          input-align="right"
        />
      <van-field
          v-model="packetParams.amount"
          type="number"
          label="金额"
          placeholder="请输入红包金额"
          input-align="right"
        />
      <van-field
          v-model="packetParams.num"
          type="number"
          label="数量"
          placeholder="请输入红包数量"
          input-align="right"
        />
        <van-cell title="兑换码">
          <template #value>
            <van-switch v-model="packetParams.dh_code"></van-switch>
          </template>
        </van-cell>
    </van-dialog>
  </div>
</template>

<style scoped lang="less">
.draw-item {
  font-size: 12px;
  padding: 10px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
